import Variable from "../pages/constants/index"
//坑点-前端会默认找目录下的index文件
//原生的微信小程序不能找，必须拼上全路径

import { ResponseData} from "../pages/type/common"
import { HttpMethod } from "../pages/type/enum"


export default class RequestHttp{
  static get<T>(url:string, params?:object){
    return request<T>(url, HttpMethod.GET, params)
  }

  static post<T>(url:string,data?:object){
    return request<T>(url, HttpMethod.POST, data)
  }

  static put<T>(url:string,data?:object){
    return request<T>(url, HttpMethod.PUT, data)
  }

  static delete<T>(url:string,data?:object){
    return request<T>(url, HttpMethod.DELETE, data)
  }
}

function request <T>(url: string, method: HttpMethod, data?: object) {
  // Promise要确定返回的类型
  return new Promise<T>((resolve,reject) => {
    // code msg data: ?
    wx.request <ResponseData<T>>({
       //  添加了多种容错判断 可以支持头条 可以支持英雄百科
      url: (data as { isTouTiao: boolean })?.isTouTiao ? Variable.TOUTIAO_URL + url : Variable.BASE_URL + url,
      method,
      data, // axios是get参数是params，post/put参数是data
      success(res){
        if (res.data.code === 200 || res.data.message==='OK') {
           // 此时认为成功
           resolve(res.data.data) // 这里不能反推类型
           // pending = fullfiled
        }else{
          wx.showToast({
            title: res.data.msg, // 弹出错误信息
            icon: 'error' // 错误图标
          })
          reject(new Error(res.data.msg))
          // pending => rejected
        }
      },
      fail(res) {
        reject(new Error(res.errMsg))
       }
    })
   // axios的get参数要传递params字段
   // axios的postbody参数要传递data字段
   // wx.request一律都叫data
  })
  // wx.request不支持promise
 }